package com.gzyj.web.api.yw;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzyj.data.common.ResponseMsg;
import com.gzyj.data.web.yw.SettingParam;
import com.gzyj.data.web.yw.cmd.TxParam;
import com.gzyj.pojo.anbiao.AnbiaoTerminalParamTx;
import com.gzyj.pojo.web.dept.GzyjDeptTree;
import com.gzyj.pojo.web.yw.AnbiaoVehicleTerminalCommand;
import com.gzyj.web.mapper.yw.AnbiaoTerminalParamTxMapper;
import com.gzyj.web.mapper.yw.AnbiaoVehicleTerminalCommandMapper;
import com.gzyj.web.utils.IntUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("api/yw/zlxf")
public class ZlxfApi {

    private void buildChildren(AnbiaoVehicleTerminalCommand parentNode, List<AnbiaoVehicleTerminalCommand> allNodes) {
        List<AnbiaoVehicleTerminalCommand> children = new ArrayList<>();
        for (AnbiaoVehicleTerminalCommand node : allNodes) {
            if (node.getParentId() != null && node.getParentId().equals(parentNode.getCmdId())) {
                children.add(node);
                buildChildren(node, allNodes);
            }
        }
        if (!children.isEmpty()) {
            parentNode.setChildren(children);
        }

    }

    @Autowired
    private AnbiaoVehicleTerminalCommandMapper anbiaoVehicleTerminalCommandMapper;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Autowired
    RedisTemplate<String, Object> clusterRedisTemplate;

    @Value("${redis.key.vehicle.cmdrs}")
    private String VehicleZdCMDRS;

    @PostMapping("getZlTree")
    public ResponseMsg<List<AnbiaoVehicleTerminalCommand>> getZlTree() {

        List<AnbiaoVehicleTerminalCommand> list = anbiaoVehicleTerminalCommandMapper.selectList(null);

        // 根节点列表
        List<AnbiaoVehicleTerminalCommand> rootNodes = new ArrayList<>();
        for (AnbiaoVehicleTerminalCommand node : list) {
            if (node.getParentId() == 0) {
                rootNodes.add(node);
            }
        }
        // 递归构建树
        for (AnbiaoVehicleTerminalCommand rootNode : rootNodes) {
            buildChildren(rootNode, list);
        }
        return new ResponseMsg<>(200, "success", rootNodes);

    }

    @Value("${kafka.queue.down}")
    private String queueDown;

    @PostMapping("send")
    public ResponseMsg<Object> sendCommnd(@RequestParam("json") String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> verifyCodes = new ArrayList<>();
        if (jsonObject.getString("status").equalsIgnoreCase("search")) {
            //查询
            if (jsonObject.getString("type").equalsIgnoreCase("txParam")) {
                TxParam txParam = JSON.parseObject(json, TxParam.class);
                for (String sim : txParam.getSimNos()) {
                    String verifycode = IntUtil.generateVerificationCode();
                    JSONObject param = new JSONObject();
                    param.put("seq", verifycode);
                    param.put("cmdID", 0x8106);
                    param.put("ipAddress", sim);
                    param.put("sendTime", sdf.format(new Date()));

                    JSONArray parmIDList = new JSONArray();
                    parmIDList.add(0x0002);
                    parmIDList.add(0x0003);
                    parmIDList.add(0x0004);
                    parmIDList.add(0x0005);
                    parmIDList.add(0x0006);
                    parmIDList.add(0x0007);
                    parmIDList.add(0x0010);
                    parmIDList.add(0x0011);
                    parmIDList.add(0x0012);
                    parmIDList.add(0x0013);
                    parmIDList.add(0x0014);
                    parmIDList.add(0x0015);
                    parmIDList.add(0x0016);
                    parmIDList.add(0x0017);
                    param.put("parmIDList", parmIDList);
                    kafkaTemplate.send(queueDown, JSON.toJSONString(param, SerializerFeature.DisableCircularReferenceDetect));
                    Map<String, Object> data = new HashMap<>();
                    data.put("sim", sim);
                    data.put("verifycode", verifycode);
                    verifyCodes.add(data);
                }

            }
        }else if(jsonObject.getString("status").equalsIgnoreCase("send")){

            if (jsonObject.getString("type").equalsIgnoreCase("txParam")){

                TxParam txParam = JSON.parseObject(json, TxParam.class);
                for (String sim : txParam.getSimNos()) {
                    String verifycode = IntUtil.generateVerificationCode();
                    JSONObject param = new JSONObject();
                    param.put("seq", verifycode);
                    param.put("cmdID", 0x8103);
                    param.put("ipAddress", sim);
                    param.put("sendTime", sdf.format(new Date()));

                    JSONArray paraList = new JSONArray();

                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0002+",\"paraValue\":\""+txParam.getTcpTimeout()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0003+",\"paraValue\":\""+txParam.getTcpR()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0004+",\"paraValue\":\""+txParam.getUdpTimeout()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0005+",\"paraValue\":\""+txParam.getUdpR()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0006+",\"paraValue\":\""+txParam.getSmsTimeout()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0007+",\"paraValue\":\""+txParam.getSmsR()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0010+",\"paraValue\":\""+txParam.getMasterAPN()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0011+",\"paraValue\":\""+txParam.getMasterUserName()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0012+",\"paraValue\":\""+txParam.getMasterPassword()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0013+",\"paraValue\":\""+txParam.getMasterIp()+":"+txParam.getMasterPort()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0014+",\"paraValue\":\""+txParam.getSlaveAPN()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0015+",\"paraValue\":\""+txParam.getSlaveUserName()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0016+",\"paraValue\":\""+txParam.getSlavePassword()+"\"}"));
                    paraList.add(JSON.parseObject("{\"cmdID\":"+0x0017+",\"paraValue\":\""+txParam.getSlaveIp()+":"+txParam.getSlavePort()+"\"}"));
                    param.put("paraList", paraList);
                    kafkaTemplate.send(queueDown, JSON.toJSONString(param, SerializerFeature.DisableCircularReferenceDetect));

                }



            }

        }


        return new ResponseMsg<>(200, "success", verifyCodes);
    }

    @Autowired
    private AnbiaoTerminalParamTxMapper anbiaoTerminalParamTxMapper;

    @PostMapping("getSearchRS")
    public ResponseMsg<Object> getSearchRS(@RequestParam("json") String json) {
        JSONArray jsonArray = JSONArray.parseArray(json);
        Map<String, Object> result = new HashMap<>();
        Integer successCnt=0;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jobj = jsonArray.getJSONObject(i);
            Object obj = clusterRedisTemplate.opsForValue().get(VehicleZdCMDRS + jobj.getString("sim") + ":" + 0x0104 + ":" + jobj.getString("verifycode"));
            if (obj != null) {
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect));
                Map<String, Object> rs = new HashMap<>();
                if (jsonObject.containsKey("terminalParams") && jsonObject.getJSONArray("terminalParams").size() > 0) {

                    long cnt = jsonObject.getJSONArray("terminalParams").stream().filter(e -> {
                        JSONObject tmp = (JSONObject) e;
                        return tmp.getInteger("paramId") == 0x0002;
                    }).count();

                    if (cnt > 0) {
                        //通讯参数
                        AnbiaoTerminalParamTx terminalParamTx = anbiaoTerminalParamTxMapper.selectOne(new QueryWrapper<AnbiaoTerminalParamTx>().eq("simNo", jobj.getString("sim")));
                        rs.put(jobj.getString("sim"), terminalParamTx);
                    }

                }


                Map<String, Object> data = new HashMap<>();

                if (rs.size() > 0) {
                    data.put("status", "查询成功");
                    data.put("data", rs);
                    successCnt++;
                }

                result.put(jobj.getString("sim"), data);

            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("status", "正在查询");
                result.put(jobj.getString("sim"), data);
            }
        }

        if (result.size() ==successCnt) {
            return new ResponseMsg<>(200, "success", result);
        }


        return new ResponseMsg<>(201, "success", result);
    }


}
